package com.chenfan.mcn.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenfan.mcn.enums.OperateLockEnum;
import com.chenfan.mcn.extension.Res;
import com.chenfan.common.extension.validation.groups.Add;
import com.chenfan.common.extension.validation.groups.Modify;
import com.chenfan.common.extension.lock.DistributedLockTemplate;
import com.chenfan.mcn.model.BrandInfo;
import com.chenfan.mcn.model.dto.BrandInfoQueryDTO;
import com.chenfan.mcn.model.dto.BrandInfoSaveDTO;
import com.chenfan.mcn.model.vo.BrandInfoSelectVO;
import com.chenfan.mcn.service.BrandInfoService;
import com.chenfan.privilege.common.config.UrlAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 品牌信息管理
 * @author wulg
 * @since 2023-11-02
 */
@RestController
@RequestMapping("/brandInfo")
public class BrandInfoController {

    @Autowired
    private BrandInfoService brandInfoService;

    /**
     * 分页查询品牌信息
     * @param dto
     * @return
     */
    @PostMapping("/getPage")
    public Res<Page<BrandInfo>> getPage(@Validated @RequestBody BrandInfoQueryDTO dto) {
        return Res.ok(brandInfoService.getPage(dto));
    }

    /**
     * 通过关键字动态搜索品牌TOP30
     * @param keyword 关键字
     * @param status 状态：0停用、1启用
     * @return
     */
    @GetMapping("/search")
    public Res<List<BrandInfoSelectVO>> search(@RequestParam(name = "keyword", defaultValue = "") String keyword,
                                               @RequestParam(required = false) Integer status) {
        return Res.ok(brandInfoService.search(keyword, status));
    }

    /**
     * 新建
     * @param dto
     * @return 品牌主键ID
     */
    @UrlAuth({"mcnBrand_add"})
    @PostMapping("/add")
    public Res<Long> add(@Validated(Add.class) @RequestBody BrandInfoSaveDTO dto) {
        return Res.ok(brandInfoService.save(dto));
    }

    /**
     * 修改
     * @param dto
     * @return 品牌主键ID
     */
    @UrlAuth({"mcnBrand_edit"})
    @PostMapping("/update")
    public Res<Long> update(@Validated(Modify.class) @RequestBody BrandInfoSaveDTO dto) {
        return Res.ok(DistributedLockTemplate.execute(OperateLockEnum.BRAND_INFO.generateKey(dto.getId()),
                () -> brandInfoService.save(dto)));
    }


    /**
     * 修改状态
     *
     * @param id     品牌主键ID
     * @param status 状态
     * @return boolean
     */
    @UrlAuth({"mcnBrand_enable", "mcnBrand_forbidden"})
    @GetMapping("/changeStatus")
    public Res<Boolean> changeStatus(@RequestParam Long id, @RequestParam Integer status) {
        return Res.ok(DistributedLockTemplate.execute(OperateLockEnum.BRAND_INFO.generateKey(id),
                () -> brandInfoService.changeStatus(id, status)));
    }
}
